/**
 *
 */
package com.jhws.sys.appUser.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.jhws.business.local.bo.LocalConstant;
import com.jhws.business.local.service.LocalService;
import com.jhws.util.LogHelper;
import org.apache.commons.lang.StringUtils;
import com.jhws.business.comm.bo.TblCommDimBo;
import com.jhws.sys.appUser.bo.TblSipAcountBindings;
import com.jhws.sys.appUser.bo.TblSipAcountDimBo;
import com.jhws.util.security.CryptionData;
import com.jhws.util.GetId;
import com.jhws.common.base.bo.Global;
import com.jhws.common.PropertiesReader;
import com.jhws.core.db.BaseDao;
import com.jhws.business.comm.service.ITblBuildingDimService;
import com.jhws.business.comm.service.ITblCommDimService;

public class TblSipAcountDimServiceSpringImpl implements ITblSipAcountDimService {

	@Resource
	private BaseDao BaseDao;

	@Resource
	private ITblBuildingDimService ITblBuildingDimService;
	@Resource
	private ITblCommDimService ITblCommDimService;
	@Resource
	private LocalService localService;

    @Override
    public TblSipAcountDimBo getSipAccountByUser(String username) {
		String where = "from TblSipAcountDimBo where username = '"+username+"'";
		if (localService.isLanMode()) {
			where += " and is_synch != '" + LocalConstant.SYNCH_STATE_DEL + "'";
		}
        List<TblSipAcountDimBo> list = BaseDao.findList(where);
        return list!=null && list.size()>0?list.get(0):null;
    }

    public void save(TblSipAcountDimBo bo) throws Exception {
		bo.setIsSynch(LocalConstant.SYNCH_STATE_NO);
		BaseDao.saveOrUpdate(bo);
	}

	public List<TblSipAcountDimBo> findTblSipAcountDimByWhere(String whereClause) throws Exception {
		if (localService.isLanMode()) {
			whereClause += " and is_synch != '" + LocalConstant.SYNCH_STATE_DEL + "'";
		}
		return BaseDao.findList("from TblSipAcountDimBo "+whereClause);
	}

	public TblSipAcountDimBo findTblSipAcountDimById(String acountId) {
		if (localService.isLanMode()) {
			return BaseDao.get(" from TblSipAcountDimBo where is_synch != '" + LocalConstant.SYNCH_STATE_DEL + "' and acount_id='"+acountId+"'");
		}
		return BaseDao.get(TblSipAcountDimBo.class,acountId);
	}

	public void removeSipAcountDim(String acountId) {
		BaseDao.delete(TblSipAcountDimBo.class,acountId);
	}

	public void remove(String username) {
    	if (localService.isLanMode()){
            BaseDao.executeHql("update TblSipAcountDimBo set is_synch='" + LocalConstant.SYNCH_STATE_DEL + "' where username='" + username + "'");
		} else {
            BaseDao.deleteByColumns("TblSipAcountDimBo", "username", username);
        }
	}

	public String getPasswordMD5(String username, String password) throws Exception {
		String domain = PropertiesReader.getProperty("sipDomain");
		if (domain.isEmpty()) {
			throw new Exception("sipDomain in app.properties not found!!!");
		}
		String MD5Src = new String(username + ":" + domain + ":" + password);
		return (new CryptionData()).MD5EncryptionStringData(MD5Src);
	}


	public void removeByComm(String commCode) {
        if (localService.isLanMode()){
            BaseDao.executeHql("update TblSipAcountBindings set is_synch='" + LocalConstant.SYNCH_STATE_DEL + "' where binding like '" + commCode + "%' and binding_type != 'villa'");
            BaseDao.executeHql("update TblSipAcountDimBo set is_synch='" + LocalConstant.SYNCH_STATE_DEL + "' where username like '" + commCode + "_%'");
        } else {
            /* 删除绑定关系 */
            BaseDao.deleteByWhere("TblSipAcountBindings", "binding like '" + commCode + "%' and binding_type != 'villa'");
            /* 删除小区相关sip账号 */
            BaseDao.deleteByWhere("TblSipAcountDimBo", "username like '" + commCode + "_%'");
        }
	}

	@Override
	public String addSipAccount(String username, String password, String type, boolean isMd5) throws Exception {

		// TODO Auto-generated method stub
		String accountId = null;
		if ((accountId = isUserExist(username)) != null)
			return accountId;

		TblSipAcountDimBo sipAcountBo = new TblSipAcountDimBo();
		sipAcountBo.setAcountId(GetId.randomID());
        if (password != null) {
            sipAcountBo.setPassword(isMd5 ? password : getPasswordMD5(username, password));
        }
		sipAcountBo.setType(type);
		sipAcountBo.setUsername(username);
		save(sipAcountBo);
		return sipAcountBo.getAcountId();
	}

	@Override
	public String isUserExist(String username) {
		// TODO Auto-generated method stub
		try {
			String where = "where 1=1 and username = '" + username + "'";
			if (localService.isLanMode()) {
				where += " and is_synch != '" + LocalConstant.SYNCH_STATE_DEL + "'";
			}
			List<TblSipAcountDimBo> list = findTblSipAcountDimByWhere(where);
			if (list.size() != 0)
				return list.get(0).getAcountId();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public List<TblSipAcountBindings> getBindingsByUser(String username) {
    	String where = "from TblSipAcountBindings where 1=1 and username ='" + username + "'";
		if (localService.isLanMode()) {
			where += " and is_synch != '" + LocalConstant.SYNCH_STATE_DEL + "'";
		}
		return BaseDao.findList(where);
	}

	@Override
	public List<TblSipAcountBindings> findBindingsByBindingOrType(String binding, String binding_type) {
    	String where = "from TblSipAcountBindings where 1=1 and binding ='" + binding + "' and binding_type = '" + binding_type + "'";
		if (localService.isLanMode()) {
			where += " and is_synch != '" + LocalConstant.SYNCH_STATE_DEL + "'";
		}
		// TODO Auto-generated method stub
		return BaseDao.findList(where);
	}

	private TblSipAcountBindings genSipBinding(String username, String bindingName, String bindingType, int pstn,
			boolean checkDb) {

		TblSipAcountBindings binding = null;
		boolean newSipBindings = true;
		if (checkDb) {
			String where = "from TblSipAcountBindings where 1=1 and username ='" + username + "' and binding = '" + bindingName + "'";
			if (localService.isLanMode()) {
				where += " and is_synch != '" + LocalConstant.SYNCH_STATE_DEL + "'";
			}
			List<TblSipAcountBindings> blist = BaseDao.findList(where);
			if (blist.size() != 0) {
				binding = blist.get(0);
				newSipBindings = false;
			}
		}

		if (newSipBindings) {
			binding = new TblSipAcountBindings();
			binding.setId(GetId.randomID());
			binding.setUsername(username);
			binding.setBinding(bindingName);
		}
		binding.setBindingType(bindingType);
		binding.setPstn(pstn);
		return binding;
	}

	public TblSipAcountBindings addSipBinding(String username, String bindingName, String bindingType, int pstn) {
		TblSipAcountBindings binding = genSipBinding(username, bindingName, bindingType, pstn, true);
		binding.setIsSynch(LocalConstant.SYNCH_STATE_NO);
		BaseDao.save(binding);
		return binding;
	}

	/**
	 * @Comment: 为每个用户生成默认的绑定列表，默认的列表包括围墙机，用户所在单元的门口机的监视列表和开锁列表。
	 * @Param:
	 */
	public List<TblSipAcountBindings> genDefaultSipUnlockMonitorBindingList(String username, String RoomInfoNum) {
		try {
			List<TblSipAcountBindings> list = new ArrayList<TblSipAcountBindings>();
			/* 添加门口机设备开锁监视绑定关系 */
			int device_number = ITblBuildingDimService.getUnitDevNumber(RoomInfoNum);
			for (int i = 1; i <= device_number; i++) {
				list.add(genSipBinding(username, RoomInfoNum.substring(0, 8) + "000" + i,
						Global.BINDING_TYPE_UNLOCK_MONITOR, 0, false));
			}

			List<TblCommDimBo> tblComms = ITblCommDimService
					.findTblCommDimByWhere("where 1=1 and comm_code = '" + RoomInfoNum.substring(0, 4) + "'");
			if (tblComms.size() != 0) {
				for (int i = 0; i < tblComms.get(0).getGateDevNum(); i++) {
					list.add(genSipBinding(username, RoomInfoNum.substring(0, 4) + "0000000" + (char) ('a' + i),
							Global.BINDING_TYPE_UNLOCK_MONITOR, 0, false));
				}
			}
			return list;

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	public void updateSipBinding(TblSipAcountBindings tblSipAcountBindings) {
		if (StringUtils.isEmpty(tblSipAcountBindings.getId())) {
			return;
		}
		TblSipAcountBindings t = (TblSipAcountBindings) BaseDao.getSessionFactory().getCurrentSession()
				.merge(tblSipAcountBindings);
		t.setIsSynch(LocalConstant.SYNCH_STATE_NO);
		BaseDao.save(t);
	}

	public void removeSipBinding(String username, String binding) {
        if (localService.isLanMode()) {
            BaseDao.executeHql("update TblSipAcountBindings set is_synch='" + LocalConstant.SYNCH_STATE_DEL + "' where username='" + username + "' and binding = '" + binding + "'");
        }else {
            BaseDao.deleteByWhere("TblSipAcountBindings", "username = '" + username + "' and binding = '" + binding + "'");
        }
    }

	@Override
	public void removeSipBindingById(String id) {
        if (localService.isLanMode()) {
            BaseDao.executeHql("update TblSipAcountBindings set is_synch='" + LocalConstant.SYNCH_STATE_DEL + "' where acount_id='" + id + "'");
        }else {
            // TODO Auto-generated method stub
            BaseDao.deleteByWhere("TblSipAcountBindings", "acount_id = '" + id + "'");
        }
	}

	@Override
	public List<TblSipAcountBindings> findTblSipAcountBindingsByWhere(String whereClause) throws Exception {
		String where = "from TblSipAcountBindings " + whereClause;
		if (localService.isLanMode()) {
			where += " and is_synch != '" + LocalConstant.SYNCH_STATE_DEL + "'";
		}
		// TODO Auto-generated method stub
		return BaseDao.findList(where);
	}
}
